<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" >
        <el-form-item>
          <el-input v-model="keywords" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery" >查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" >新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="Pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <!--childPet: []dirPath: "/1" id: 1 manager: null manager_id: 324 name: "宠物1"
      parentPet: null parent_id: nullsn: "dept1" state: 1-->
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="120" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <el-span v-if="scope.row.state==1" style="color:#008000;" >上架</el-span>
          <el-span v-else-if="scope.row.state==0" style="color:red;" size="small" >下架</el-span>
        </template>
      </el-table-column>
      <el-table-column prop="type.name" label="宠物类型" width="120" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="120" sortable>
      </el-table-column>
      <el-table-column prop="user.username" label="领养人" width="120" sortable>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" width="120" sortable>
        <template scope="scope">
          <el-span v-if="scope.row.searchMasterMsgId" style="color:#008000;" >寻主信息</el-span>
          <el-span v-else style="color:red;" size="small" >店铺饲养</el-span>
        </template>
      </el-table-column>


      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"  >编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑和新增对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属店铺">
          <el-select v- v-model="saveForm.shopId" clearable placeholder="请选择宠物经理">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物类型">
          <!--          <el-input  v-model="saveForm.parent_id"></el-input>-->
          <el-cascader v-model="saveForm.type"
                       :options="typeTree"
                       :props="{ checkStrictly: true, label:'name',value:'id'}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item prop="resources" label="宠物图片">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.petDetail.intro" :options="quillOption" v-if="saveForm.petDetail">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor v-model="saveForm.petDetail.adoptNotice" :options="quillOption" v-if="saveForm.petDetail">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
/*import util from '../../common/js/util'*/
//import NProgress from 'nprogress'
/*import { getPetListPage, removePet, batchRemovePet, savePet, addPet } from '../../api/api';*/
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';
//引入Vue的ueditor的资源
// import { quillEditor } from "vue-quill-editor"; //调用编辑器
// import 'quill/dist/quill.core.css';
// import 'quill/dist/quill.snow.css';
// import 'quill/dist/quill.bubble.css';
// import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      Pets: [],
      totals: 22,
      currentPage:1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列
      // 高级查询
      keywords:'',
      // 添加和修改
      title:'',
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
        costprice: [
          { required: true, message: '请输入成本价', trigger: 'blur' }
        ],
        saleprice: [
          { required: true, message: '请输入销售价', trigger: 'blur' }
        ],
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        type: null,
        resources: '',
        state: 0,
        shopId: null,
        petDetail:{
          intro:'',
          adoptNotice: ''
        }
      },
      shops:[],
      typeTree:[],
      fileList:[]
    }
  },
  methods: {

    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getPets();
    },
    //获取用户列表
    getPets() {
      let para = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        "keywords": this.keywords
      };
      //忙等待启动
      this.listLoading = true;
      //NProgress.start();
      //发送异步请求
      this.$http.post("/pet",para).then(res=>{
        this.listLoading = false;
        this.totals = res.data.totals;
        this.Pets = res.data.data;
      }).catch(res=>{
        this.$message.error('错了哦，这是一条错误消息');
      })
    },

    keywordQuery(){
      this.currentPage=1;
      this.getPets();

    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/pet/"+row.id)
            .then(res=>{
              this.listLoading = false;
              if (res.data.success){
                this.$message.success("删除成功")

                let totalPage = Math.ceil(this.totals/this.pageSize); // 算出总页数

                // 如果当前页是最后一页                并且是最后一条数据                     并且不在第一页
                if (this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){

                  this.currentPage=this.currentPage-1;
                }
                this.getPets()
              }else {
                this.$message.error("网络繁忙，请稍后重试")
              }
            }).
        catch(res=>{
          this.$message.error("网络繁忙，请稍后重试")
        })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      //克隆：防止对象引用修改显示的数据
      this.title = " 修 改 ";
      this.saveForm = Object.assign({}, row);


      //判断一下：防止因type为null导致的异常
      if(this.saveForm.type){
        //对宠物类型回显的处理:{} - []
        var dirPath = this.saveForm.type.dirPath; //   /2/3/5 - [2,3,5]
        var arr = dirPath.split("/"); //  ["/","2","3","5"]
        var resultArr = [];
        for(var i=1;i<arr.length;i++){
          resultArr[i-1] = parseInt(arr[i]); //将字符串转成整数
          //第一次：resultArr[0] = arr[1] = 2;
          //第二次：resultArr[1] = arr[2] = 3
        }
        this.saveForm.type = resultArr; //[2,3,5]
      }

      this.getShops();
      this.getTypeTree();


        //显示对话框
      this.saveFormVisible = true;

    },
    //显示新增界面
    handleAdd: function () {

      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        type: null,
        resources: null,
        state: 0,
        shopId: null,
        petDetail:{ //petDetail
          intro:'',
          adoptNotice: ''
        }
      };
      //清空列表
      this.fileList = [];
      this.title='添加',
      this.getTypeTree();
      this.getShops();
      this.saveFormVisible = true;
    },
    //编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            var arr = this.saveForm.type; //[ 3, 8 ]
            if(arr){
              //防止400错误
              para.type = null;
              para.typeId = arr[arr.length-1]
            }

            this.$http.put("/pet",para).then(res=>{
              this.saveLoading = false;
              this.saveFormVisible = false;
              if (res.data.success){

                this.$message.success("操作成功");
                this.getPets();
              }else {
                this.$message.error("网络繁忙，请稍后重试[500]")

              }
            }).catch(res=>{
              this.$message.error("网络繁忙，请稍后重试[404]")

            })



          });
        }
      });
    },


    // 批量删除
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet",ids).then(res=>{
          this.listLoading = false;
          if (res.data.success){
            this.$message.success("删除成功")
            this.currentPage=1;
            this.getPets();
          }else {
            this.$message.error("网络繁忙，请稍后重试[500]")
          }

        }).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试[404]")
        })
      }).catch(() => {

      });
    },


    getTypeTree(){
      this.$http.get("/petType/typeTree").then(res=>{
        this.typeTree= res.data;
      }).catch(res=>{

      })

    },
    handleSuccess(response, file, fileList) {
      //{ success: true, message: "操作成功", resultObj: "/group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg" }
      //console.log(response);
      //1.处理resources
      if (this.saveForm.resources) {//有值
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }

      this.fileList=[];
      if (this.saveForm.resources){
        let  arr =this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
    },

    //点击删除某一张图片的处理
    handleRemove: function (file, fileList) {
      //{url: "http://123.207.27.208/group1/M00/00/02/CgAIC2KevEeAX2T4AAEUusLjqqk161.png"}
      //console.log(file);
      //1.调用删除接口删除 fastdfs上的图片
      let url = file.url
      let path = url.substring(url.indexOf("/group"));
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功");
        }else{
          this.$message.error("删除失败");
        }
      })

      //2.对resource做处理 ：加入path="/group1/MxVcQ8663.jpg"
      // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg,/group1/MxVcQ8663.jpg
      if(this.saveForm.resources){//只有值
        //["/group1/M00cQ8663.jpg","/group1/MxVcQ8663.jpg","/group1/MxVcQ8663.jpg"]
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          if(arr[i] == path){
            //从i开始删除，向后删除1个
            arr.splice(i,1);
            break;
          }
        }
        this.saveForm.resources = arr.join(","); // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg
      }

      //3.对fileList做处理
      this.fileList = [];
      if(this.saveForm.resources){//有值
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
    },

    getShops(){
      this.$http.get("/shop").then(res=>{
        this.shops= res.data;
      }).catch(res=>{

      })

    },

    onsale(){
      var ids = this.sels.map(item => item.id);
      if (!ids || ids.length<1){
        this.$message.warning("请至少选择一只宠物")
        return ;
      }
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/onsale",ids).then(res=>{
          if (res.data.success){
            this.$message.success("上架成功");
            this.getPets();
          }

        }).catch(res=>{
          this.$message.error("系统错误！请重新输入");
        })
      }).catch(() => {

        this.$message.error("系统异常！请重新输入");


      });

      },

    offsale(){
      var ids = this.sels.map(item => item.id);
      if (!ids || ids.length<1){
        this.$message.warning("请至少选择一只宠物")
        return ;
      }
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/offsale",ids).then(res=>{
          if (res.data.success){
            this.$message.success("下架成功");
            this.getPets();
          }

        }).catch(res=>{
          this.$message.error("系统错误！请重新输入");
        })
      }).catch(() => {

        this.$message.error("系统异常！请重新输入");


      });

    },

  },


  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>